package com.hh.service.service.impl.merchant;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.hh.common.model.merchant.MerchantAdmin;
import com.hh.common.model.merchant.MerchantMenu;
import com.hh.common.model.system.SystemPermissions;
import com.hh.common.vo.merchant.MerLoginUserVo;
import com.hh.service.service.merchant.MerUserDetailsService;
import com.hh.service.service.merchant.MerchantAdminService;
import com.hh.service.service.merchant.MerchantMenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MerUserDetailsServiceImpl implements MerUserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(MerUserDetailsServiceImpl.class);

    @Autowired
    private MerchantAdminService merchantAdminService;

    @Autowired
    private MerchantMenuService merchantMenuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        MerchantAdmin user = merchantAdminService.selectUserByUserName(username);
        if (ObjectUtil.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        } else if (!user.getStatus()) {
            log.info("登录用户：{} 已被停用.", username);
            throw new UsernameNotFoundException("对不起，您的账号：" + username + " 已停用");
        }

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(MerchantAdmin user) {
        List<MerchantMenu> menuList;
        if (user.getIsSuperAdmin()) {// 超级管理员
            // 获取该商户的全部权限
            menuList = merchantMenuService.getAllPermissions(user.getMerId());
        } else {
            menuList = merchantMenuService.findPermissionByUserId(user.getId());
        }
        menuList = menuList.stream().filter(e -> StrUtil.isNotEmpty(e.getPerms())).collect(Collectors.toList());
        List<SystemPermissions> permissionsList = menuList.stream().map(e -> {
            SystemPermissions permissions = new SystemPermissions();
            permissions.setId(e.getId());
            permissions.setPid(e.getPid());
            permissions.setName(e.getName());
            permissions.setPath(e.getPerms());
            permissions.setSort(e.getSort());
            return permissions;
        }).collect(Collectors.toList());
        return new MerLoginUserVo(user, permissionsList);
    }
}
